const fs = require('fs')
const conf = require('./conf/conf.json')
const { parseTower } = require('./models/tower/parse')
const { translateKey, Display } = require('./display/general')
const { cleanObject } = require('./util/utils')

String.prototype.format = function (...params) {
    return this.replaceAll(/\{(\d+)\}/g, (s, i) => params[Number(i)])
}

const towers = {
    'DartMonkey': {},
    'BoomerangMonkey': {},
    'BombShooter': {},
    'TackShooter': {},
    'IceMonkey': {},
    'GlueGunner': {},
    'Desperado': {},
    'SniperMonkey': {},
    'MonkeySub': {},
    'MonkeyBuccaneer': {},
    'MonkeyAce': {},
    'HeliPilot': {},
    'MortarMonkey': {},
    'DartlingGunner': {},
    'WizardMonkey': {},
    'SuperMonkey': {},
    'NinjaMonkey': {},
    'Alchemist': {},
    'Druid': {},
    'Mermonkey': {},
    'BananaFarm': {},
    'SpikeFactory': {},
    'MonkeyVillage': {},
    'EngineerMonkey': {},
    'BeastHandler': {},
}

const heroes = {
    "Quincy": {},
    "Gwendolin": {},
    "StrikerJones": {},
    "ObynGreenfoot": {},
    "CaptainChurchill": {},
    "Benjamin": {},
    "Ezili": {},
    "PatFusty": {},
    "Adora": {},
    "AdmiralBrickell": {},
    "Etienne": {},
    "Sauda": {},
    "Psi": {},
    "Geraldo": {},
    "Corvus": {},
    "Rosalia": {},
    "Silas": {},
}

function walk(dir) {
    const items = fs.readdirSync(dir)
    for (let item of items) {
        const fullPath = dir + '/' + item
        const stats = fs.statSync(fullPath)
        if (stats.isDirectory()) {
            walk(fullPath)
        } else {
            const obj = JSON.parse(fs.readFileSync(fullPath))
            parseTowerData(obj, obj.baseId);
        }
    }
}

function parseTowerData(obj, tower = '') {
    if (obj.isSubTower || obj.isGeraldoItem || [
        'TransformedBaseMonkey',
        'TransformedMonkey',
        'TransformedMonkeyV2',
        'ParagonTotem-ParagonTotem'
    ].includes(obj.name)) {
        return;
    }
    if (obj.isPowerTower || obj.isPowerProTower) {
        // will parse in the future
        return;
    }
    let thing = cleanObject(parseTower(obj));
    delete thing['name']
    let str = JSON.stringify(thing, (k, v) => v instanceof Display ? v.out : v, 2);
    if (conf.showSeperateStats) {
        fs.mkdir(`${conf.outputPath}/${tower}`, () => { })
        fs.writeFile(`${conf.outputPath}/${tower}/${obj.name}.json`, str, () => { });
    }
    if (towers[obj.baseId]) {
        const saveIndex = obj.isParagon ? 'paragon' : obj.tiers.join('')
        if (!((['BeastHandler', 'MonkeyVillage']).includes(obj.baseId) && saveIndex.match(/0/g)?.length < 2)) {
            const translated = conf.translate ? translateKey(thing) : thing
            towers[obj.baseId][saveIndex] = JSON.stringify(
                translated, (k, v) => v instanceof Display ? v.out : v, null)
        }
    }
    if (heroes[obj.baseId]) {
        const saveIndex = obj.tier.toString()
        const translated = conf.translate ? translateKey(thing) : thing
        heroes[obj.baseId][saveIndex] = translated
    }
}

function saveMergedData() {
    for (let t in towers) {
        fs.writeFile(`${conf.outputPath}/${t}.json`, JSON.stringify(towers[t], null, 4), () => { })
    }
    for (let h in heroes) {
        fs.writeFile(`${conf.outputPath}/${h}.json`, JSON.stringify(heroes[h], null, 4), () => { })
    }
}

function main() {
    walk(conf.towerDataPath)
    saveMergedData()
}

try {
    main()
} catch (e) {
    console.log(e)
}